package org.light.simpleauth.easyui;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.complexverb.AddUploadDomainField;
import org.light.complexverb.DomainFieldVerb;
import org.light.complexverb.UpdateUploadDomainField;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.FieldSerialComparator;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.easyui.EasyUIPositions;
import org.light.easyuilayouts.EasyUILayout;
import org.light.generator.NamedS2SMJavascriptMethodGenerator;
import org.light.simpleauth.verb.ChangeMyPasswordUser;
import org.light.simpleauth.verb.FindMyProfileUser;
import org.light.simpleauth.verb.UpdateMyProfileUser;
import org.light.utils.DomainUtil;
import org.light.utils.FieldUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class EasyUIProfileLayout extends EasyUILayout {
	protected Set<DomainFieldVerb> domainFieldVerbs = new TreeSet<>();
	protected Domain domain;
	
	public Set<DomainFieldVerb> getDomainFieldVerbs() {
		return domainFieldVerbs;
	}

	public void setDomainFieldVerbs(Set<DomainFieldVerb> domainFieldVerbs) {
		this.domainFieldVerbs = domainFieldVerbs;
	}

	public Domain getDomain() {
		return domain;
	}

	public void setDomain(Domain domain) {
		this.domain = domain;
	}

	public EasyUIProfileLayout(Domain domain) throws Exception{
		super();
		this.domain = domain;
		this.dbType = domain.getDbType();
		this.technicalStack = domain.getTechnicalStack();		
		this.standardName = "Profile";

		for (Field f:this.domain.getPlainFields()) {
			if (f.getFieldType().equalsIgnoreCase("image")) {
				domainFieldVerbs.add(new AddUploadDomainField(this.domain,f));
				domainFieldVerbs.add(new UpdateUploadDomainField(this.domain,f));
			}
		}
	}
	
	@Override
	public StatementList generateLayoutStatements() throws Exception {
		List<Writeable> sList = new ArrayList<Writeable>();

		sList.add(new Statement(22000L,0,"<div style=\"margin:20px 0\"></div>"));
		if (this.domain.getLanguage().equalsIgnoreCase("english")) {
			sList.add(new Statement(23000L,0,"<div class=\"easyui-panel\" title=\"Update "+this.domain.getText()+" profile.\" style=\"w"+this.domain.getDomainId().getLowerFirstFieldName()+"th:700px\">"));
		}else {
			sList.add(new Statement(23000L,0,"<div class=\"easyui-panel\" title=\"更新"+this.domain.getText()+"资料\" style=\"w"+this.domain.getDomainId().getLowerFirstFieldName()+"th:700px\">"));
		}
		sList.add(new Statement(24000L,0,"<div style=\"padding:10px 60px 20px 60px\">"));
		sList.add(new Statement(25000L,0,"<form id=\"ff\" method=\"post\">"));
		sList.add(new Statement(26000L,0,"<table cellpadding=\"5\">"));
		sList.add(new Statement(27000L,0,"<input type=\"hidden\" name=\""+this.domain.getDomainId().getLowerFirstFieldName()+"\" id=\""+this.domain.getDomainId().getLowerFirstFieldName()+"\"/>"));
		sList.add(new Statement(28000L,0,"<tr><td>"+this.domain.findFieldByFixedName("userName").getText()+":</td><td><input  class='easyui-textbox' type='text' name='"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"' id='"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"' value='' data-options=\"required:false\"/></td></tr>"));
		
		long serial = 30000L;
		Set<Field> fields3 = new TreeSet<Field>(new FieldSerialComparator());
		fields3.addAll(this.domain.getPlainFields());
		Set<Field> deniedFields = new TreeSet<Field>(new FieldSerialComparator());
		deniedFields.add(this.domain.findFieldByFixedName("password"));
		deniedFields.add(this.domain.findFieldByFixedName("salt"));
		deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
		fields3 = FieldUtil.filterDeniedFields(fields3,deniedFields);
		for (Field f: fields3){
			if (f.getFieldType().equalsIgnoreCase("image")) {
				sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><img name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' width='500px' src='../images/blank.jpg'><br>"));
				sList.add(new Statement(serial,0,"<input id=\"add"+this.domain.getCapFirstDomainName()+f.getCapFirstFieldName()+"Fileupload\" type=\"file\" name=\"files[]\" data-url=\"../"+this.domain.getControllerPackagePrefix()+"profile"+this.domain.getControllerNamingSuffix()+"/addUpload"+this.domain.getCapFirstDomainName()+f.getCapFirstFieldName()+"\"><br></td></tr>"));
			} else if (f.getFieldType().equalsIgnoreCase("datetime")) {
				sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><input  class='easyui-datetimebox' type='text' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='' data-options=\"required:false,parser:parseDateTime,formatter:formatDateTime\"/></td></tr>"));
			} else if (f.getFieldType().equalsIgnoreCase("date")) {
				sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><input  class='easyui-datebox' type='text' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='' data-options=\"required:false,parser:parseDate,formatter:formatDate\"/></td></tr>"));
			} else {
				if (!(f instanceof Dropdown) && !(f.getFieldType().equalsIgnoreCase("boolean"))&&!f.isTextarea()) sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><input  class='easyui-textbox' type='text' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='' data-options=\"required:false\"/></td></tr>"));
				if (!(f instanceof Dropdown) && !(f.getFieldType().equalsIgnoreCase("boolean"))&&f.isTextarea()) sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><textarea  class='easyui-textarea' type='text' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' data-options=\"required:false\" cols='20' rows='4'></textarea></td></tr>"));
				if (!(f instanceof Dropdown) && f.getFieldType().equalsIgnoreCase("boolean")) sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><input class='easyui-radio' type='radio' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='true' checked='true'/>True<input type='radio' class='easyui-radio' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='false'/>False</td></tr>"));
				if (f instanceof Dropdown)
					sList.add(new Statement(serial,0,"<tr><td>"+f.getText()+":</td><td><input  class='easyui-combobox' type='text' name='"+f.getLowerFirstFieldName()+"' id='"+f.getLowerFirstFieldName()+"' value='' data-options=\"required:false,valueField:'"+((Dropdown)f).getTarget().getDomainId().getLowerFirstFieldName()+"',textField:'"+((Dropdown)f).getTarget().getDomainName().getLowerFirstFieldName()+"',method:'post',url:'../"+this.domain.getControllerPackagePrefix()+"profile"+this.domain.getControllerNamingSuffix()+"/listActive"+((Dropdown)f).getTarget().getCapFirstPlural()+"',loadFilter:function(data){return data.rows}\"/></td></tr>"));
			}
			serial+=1000L;
		}
		if (this.domain.hasActiveField()) {
			if ("true".equals(this.domain.getDomainActiveStr())||this.domain.getDomainActiveInteger() == 1) {
				sList.add(new Statement(serial+51000L,0,"<tr><td>"+this.domain.getActive().getText()+":</td><td><input class='easyui-radio' type='radio' name='"+this.domain.getActive().getLowerFirstFieldName()+"' id='"+this.domain.getActive().getLowerFirstFieldName()+"' value='true' checked='true'/>True<input type='radio' class='easyui-radio' name='"+this.domain.getActive().getLowerFirstFieldName()+"' id='"+this.domain.getActive().getLowerFirstFieldName()+"' value='false'/>False</td></tr>"));
			}else {
				sList.add(new Statement(serial+51000L,0,"<tr><td>"+this.domain.getActive().getText()+":</td><td><input class='easyui-radio' type='radio' name='"+this.domain.getActive().getLowerFirstFieldName()+"' id='"+this.domain.getActive().getLowerFirstFieldName()+"' value='true' />True<input type='radio' class='easyui-radio' name='"+this.domain.getActive().getLowerFirstFieldName()+"' id='"+this.domain.getActive().getLowerFirstFieldName()+"' value='false' checked='true'/>False</td></tr>"));
			}
		}
		sList.add(new Statement(serial+52000L,0,"</table>"));
		sList.add(new Statement(serial+53000L,0,"</form>"));
		sList.add(new Statement(serial+54000L,0,"<div style=\"text-align:center;padding:5px\">"));
		if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
			sList.add(new Statement(serial+55000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"updateMyProfile"+this.domain.getCapFirstDomainName()+"()\">Update "+this.domain.getText()+" profile</a>"));
			sList.add(new Statement(serial+56000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"clearForm()\">Clear</a>"));
			sList.add(new Statement(serial+57000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"$('#wchangePassword').window('open');\">Change password</a>"));
		}else{
			sList.add(new Statement(serial+55000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"updateMyProfile"+this.domain.getCapFirstDomainName()+"()\">更新"+this.domain.getText()+"资料</a>"));
			sList.add(new Statement(serial+56000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"clearForm()\">清除</a>"));
			sList.add(new Statement(serial+57000L,0,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"$('#wchangePassword').window('open');\">修改密码</a>"));
		}
		sList.add(new Statement(serial+58000L,0,"</div>"));
		sList.add(new Statement(serial+59000L,0,"</div>"));
		sList.add(new Statement(serial+60000L,0,"</div>"));
		
		if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
			sList.add(new Statement(serial+61000L,0,"<div class=\"easyui-window\" title=\"Set password\" id=\"wchangePassword\" data-options=\"iconCls:'icon-save',modal:true,closed:true\" style=\"width:600px;height:400px\">"));
		} else {
			sList.add(new Statement(serial+61000L,0,"<div class=\"easyui-window\" title=\"设置密码\" id=\"wchangePassword\" data-options=\"iconCls:'icon-save',modal:true,closed:true\" style=\"width:600px;height:400px\">"));
		}
		sList.add(new Statement(serial+62000L,1,"<div style=\"padding:10px 60px 20px 60px\">"));
		sList.add(new Statement(serial+63000L,1,"<form id=\"ffchangePassword\" method=\"post\">"));
		sList.add(new Statement(serial+64000L,1,"<input type=\"hidden\" id=\"userName\" name=\"userName\">"));
		sList.add(new Statement(serial+65000L,1,"<table cellpadding=\"5\">"));
		if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
			sList.add(new Statement(serial+66000L,2,"<tr><td>Old password:</td><td><input class='easyui-textbox' type='password' name='old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' id='old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
			sList.add(new Statement(serial+67000L,2,"<tr><td>New password:</td><td><input class='easyui-textbox' type='password' name='"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"' id='"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
			sList.add(new Statement(serial+68000L,2,"<tr><td>Confirm password:</td><td><input class='easyui-textbox' type='password' name='confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' id='confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
		} else {
			sList.add(new Statement(serial+66000L,2,"<tr><td>旧密码:</td><td><input class='easyui-textbox' type='password' name='old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' id='old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
			sList.add(new Statement(serial+67000L,2,"<tr><td>新密码:</td><td><input class='easyui-textbox' type='password' name='"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"' id='"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
			sList.add(new Statement(serial+68000L,2,"<tr><td>确认新密码:</td><td><input class='easyui-textbox' type='password' name='confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' id='confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"' value='' data-options=\"required:true\"/></td></tr>"));
		}
		sList.add(new Statement(serial+69000L,1,"</table>"));
		sList.add(new Statement(serial+70000L,1,"</form>"));
		sList.add(new Statement(serial+71000L,1,"<div style=\"text-align:center;padding:5px\">"));
		if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
			sList.add(new Statement(serial+72000L,1,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"changeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+this.domain.getCapFirstDomainName()+"()\">Reset Password</a>"));
			sList.add(new Statement(serial+73000L,1,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"$('#wchangePassword').window('close')\">Close</a>"));
		} else {
			sList.add(new Statement(serial+72000L,1,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"changeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+this.domain.getCapFirstDomainName()+"()\">重设密码</a>"));
			sList.add(new Statement(serial+73000L,1,"<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" onclick=\"$('#wchangePassword').window('close')\">关闭</a>"));
		}
		sList.add(new Statement(serial+74000L,0,"</div>"));
		sList.add(new Statement(serial+75000L,0,"</div>"));
		
		return WriteableUtil.merge(sList);
	}

	@Override
	public StatementList generateLayoutScriptStatements() throws Exception {
		List<Writeable> sList = new ArrayList<Writeable>();
		if (this.domainFieldVerbs!=null&&this.domainFieldVerbs.size()>0) {
			sList.add(new Statement(serial,0,"$(function () {"));	
			serial+=1000L;
			for (DomainFieldVerb dfv:this.domainFieldVerbs) {
				if(dfv instanceof AddUploadDomainField) {
					JavascriptBlock uploadBlock = dfv.generateEasyUIJSButtonBlock();
					StatementList  slupload = uploadBlock.getMethodStatementList();
					
					slupload.setSerial(serial);
					sList.add(slupload);
					serial+= 1000L;
				}
			}
			sList.add(new Statement(serial+2000L,0,"});"));
		}
		
		Set<Field> deniedFields = new TreeSet<>();
		deniedFields.add(this.domain.findFieldByFixedName("password"));
		deniedFields.add(this.domain.findFieldByFixedName("salt"));
		deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
		
		sList.add(new Statement(serial+3000L,0,"$(document).ready(function(){"));
		FindMyProfileUser findProfile = new FindMyProfileUser(this.domain,deniedFields);
		sList.add(new Statement(serial+4000L,0,StringUtil.lowerFirst(findProfile.getVerbName())+"();"));
		serial += 5000L;
		
		List<Domain> translateDomains = new ArrayList<Domain>();
		for (Field f: this.domain.getPlainFields()){
			if (f instanceof Dropdown){
				Dropdown dp = (Dropdown)f;
				Domain target = dp.getTarget();
				if (!target.isLegacy()&&!DomainUtil.inDomainList(target, translateDomains)){
					translateDomains.add(target);
				}
			}
		}
		
		for (Domain d:translateDomains) {
			sList.add(new Statement(serial,0,"translate"+d.getCapFirstPlural()+" = translateListActive"+d.getCapFirstPlural()+"();"));
			serial += 1000L;
		}
		sList.add(new Statement(serial,0,"});"));
		
		serial += 1000L;
		
		JavascriptMethod slFindMyProfileUserJm = ((EasyUIPositions)new FindMyProfileUser(this.domain,deniedFields)).generateEasyUIJSActionMethod();
		if(	slFindMyProfileUserJm != null) {
			StatementList slFindMyProfileUserAction = slFindMyProfileUserJm.generateMethodStatementListIncludingContainer(serial,0);
			sList.add(slFindMyProfileUserAction);
		}
		
		JavascriptMethod slChangeMyPasswordUserJm = ((EasyUIPositions)new ChangeMyPasswordUser(this.domain)).generateEasyUIJSActionMethod();
		if(	slChangeMyPasswordUserJm != null) {
			StatementList slChangeMyPasswordUserAction = slChangeMyPasswordUserJm.generateMethodStatementListIncludingContainer(serial+1000L,0);
			sList.add(slChangeMyPasswordUserAction);
		}
		
		JavascriptMethod slUpdateMyProfileUserJm = ((EasyUIPositions)new UpdateMyProfileUser(this.domain,deniedFields)).generateEasyUIJSActionMethod();
		if(	slUpdateMyProfileUserJm != null) {
			StatementList slUpdateMyProfileUserAction = slUpdateMyProfileUserJm.generateMethodStatementListIncludingContainer(serial+2000L,0);
			sList.add(slUpdateMyProfileUserAction);
		}
		
		serial += 3000L;
		sList.add(NamedS2SMJavascriptMethodGenerator.generateParseBooleanMethod().generateMethodStatementList(serial+1000L));
		sList.add(NamedS2SMJavascriptMethodGenerator.generateParseBooleanIntMethod().generateMethodStatementList(serial+1500L));
		sList.add(NamedS2SMJavascriptMethodGenerator.generateParseIntNegMethod().generateMethodStatementList(serial+1600L));
		sList.add(NamedS2SMJavascriptMethodGenerator.generateIsBlankMethod().generateMethodStatementList(serial+2000L));
		
		if (this.domain.containsDateTime()) {
			sList.add(NamedS2SMJavascriptMethodGenerator.generateParseDateTimeMethod().generateMethodStatementList(serial+4000L));
			sList.add(NamedS2SMJavascriptMethodGenerator.generateFormatDateTimeMethod().generateMethodStatementList(serial+5000L));
			sList.add(NamedS2SMJavascriptMethodGenerator.generateParseDateMethod().generateMethodStatementList(serial+6000L));
			sList.add(NamedS2SMJavascriptMethodGenerator.generateFormatDateMethod().generateMethodStatementList(serial+7000L));
		}
		
		serial += 8000L;
		
		for (Domain d:translateDomains) {
			Dropdown dp = new Dropdown();
			dp.setTarget(d);
			sList.add(dp.generateTranslateMethod().generateMethodStatementList(serial));
			sList.add(dp.generateTranslateListActiveMethod().generateMethodStatementList(serial+1000L));
			serial+=2000L;
		}

		return WriteableUtil.merge(sList);
	}

	@Override
	public boolean parse() throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
}
